.globl argmax

.text
# =================================================================
# FUNCTION: Given a int vector, return the index of the largest
#	element. If there are multiple, return the one
#	with the smallest index.
# Arguments:
# 	a0 (int*) is the pointer to the start of the vector
#	a1 (int)  is the # of elements in the vector
# Returns:
#	a0 (int)  is the first index of the largest element
#
# If the length of the vector is less than 1, 
# this function exits with error code 7.
# =================================================================
argmax:
    # Prologue
    addi sp, sp, -24
    sw ra, 0(sp)
    sw s0, 4(sp)
    sw s1, 8(sp)
    sw s2, 12(sp)
    sw s3, 16(sp)
    sw s4, 20(sp)

    # save arguments
    add s0, a0, x0

    # initial
    add s1, x0, x0
    lw s3, 0(s0)
    add s4, x0, x0

    # if a1 >= 1, goto loop_start
    addi s2, x0, 1
    bge a1, s2, loop_start
    # call exit2
    addi a1, x0, 7
    jal ra, exit2


loop_start:
    # if s1 == a1, goto loop_end
    beq s1, a1, loop_end
    slli s2, s1, 2
    add s2, s0, s2
    lw s2, 0(s2)  # s2 = a0[s1]
    # if a0[s1] > s3, goto loop_continue
    blt s3, s2, loop_continue
    # s1++
    addi s1, s1, 1
    j loop_start


loop_continue:
    # s3 = s2
    add s3, s2, x0
    add s4, s1, x0
    # s1++
    addi s1, s1, 1
    j loop_start


loop_end:
    add a0, s4, x0

    # Epilogue
    lw ra, 0(sp)
    lw s0, 4(sp)
    lw s1, 8(sp)
    lw s2, 12(sp)
    lw s3, 16(sp)
    lw s4, 20(sp)
    addi sp, sp, 24

    ret
